package com.ygqh.baby.service.wdtqyb.http;

import com.foxinmy.weixin4j.http.*;
import com.foxinmy.weixin4j.http.apache.FormBodyPart;
import com.foxinmy.weixin4j.http.apache.HttpMultipartMode;
import com.foxinmy.weixin4j.http.apache.MultipartEntity;
import com.foxinmy.weixin4j.http.entity.FormUrlEntity;
import com.foxinmy.weixin4j.http.entity.HttpEntity;
import com.foxinmy.weixin4j.http.factory.HttpClientFactory;
import com.ygqh.baby.model.wdt.qyb.WdtQybResult;
import com.ygqh.baby.service.wdtqyb.exception.WdtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Map;

/**
 * 负责请求的执行
 *
 * @see
 */
public class WdtRequestExecutor {

    private static final Logger logger = LoggerFactory.getLogger(WdtRequestExecutor.class);

    private static final int SUCCESS_CODE = 0;

    private final HttpClient httpClient;

    public WdtRequestExecutor() {
        this.httpClient = HttpClientFactory.getInstance();
    }

    /**
     * Post方法执行请求
     *
     * @param url  请求URL
     * @param body 参数内容
     * @return 响应
     * @throws WdtException
     */
    public WdtResponse post(String url, Map<String, String> body) throws WdtException {
        logger.info("post request -> {}", body == null ? "{}" : body.toString());
        HttpEntity entity = new FormUrlEntity(body);
        HttpRequest request = new HttpRequest(HttpMethod.POST, url);
        request.setEntity(entity);
        return doRequest(request);
    }

    /**
     * Post方法执行请求，用于文件上传
     *
     * @param url       请求URL
     * @param bodyParts 文件内容
     * @return 响应
     * @throws WdtException
     */
    public WdtResponse post(String url, FormBodyPart... bodyParts) throws WdtException {
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("UTF-8"));
        for (FormBodyPart bodyPart : bodyParts) {
            entity.addPart(bodyPart);
        }
        HttpRequest request = new HttpRequest(HttpMethod.POST, url);
        request.setEntity(entity);
        return doRequest(request);
    }

    /**
     * Get方法执行微信请求
     *
     * @param url        请求URL，如：https://api.weixin.qq.com/cgi-bin/token
     * @param parameters url上的参数，如:new URLParameter("appid",xxxxx)
     * @return 响应
     * @throws WdtException
     */
    public WdtResponse get(String url, URLParameter... parameters) throws WdtException {
        // always contain the question mark
        StringBuilder buf = new StringBuilder(url);
        if (parameters != null && parameters.length > 0) {
            buf.append("&").append(FormUrlEntity.formatParameters(Arrays.asList(parameters)));
        }
        HttpRequest request = new HttpRequest(HttpMethod.GET, buf.toString());
        return doRequest(request);
    }

    /**
     * 执行请求
     *
     * @param request 请求
     * @return 响应
     * @throws WdtException
     */
    public WdtResponse doRequest(HttpRequest request) throws WdtException {
        try {
            HttpResponse httpResponse = httpClient.execute(request);
            WdtResponse response = new WdtResponse(httpResponse);
            System.out.println(response.getAsString());
            handleResponse(response);
            return response;
        } catch (HttpClientException e) {
            throw new WdtException(e);
        }
    }

    /**
     * handle the weixin response
     *
     * @param response 请求响应
     * @throws WdtException
     */
    protected void handleResponse(WdtResponse response) throws WdtException {
        WdtQybResult result = response.getAsResult();
        if (SUCCESS_CODE != result.getCode()) {
            throw new WdtException(result.getCode() + "", result.getMessage());
        }
    }

    public HttpClient getExecuteClient() {
        return httpClient;
    }

}
